package com.stars.easyms.datasource.interceptor;

import com.stars.easyms.datasource.exception.DataSourceInterceptorException;
import com.stars.easyms.datasource.holder.EasyMsMasterSlaveDataSourceHolder;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.Method;

/**
 * <p>className: FixedDataSourceInterceptor</p>
 * <p>description: FixedDataSource注解拦截器：Controller、Service、Dao越上层优先级越高</p>
 *
 * @author guoguifang
 * @date 2019/12/10 9:42
 * @since 1.4.2
 */
public final class FixedDataSourceInterceptor extends BaseEasyMsDatasourceMethodInterceptor {

    @Override
    public Object interceptMybatisMethod(MethodInvocation methodInvocation, Class<?> mapperInterface, Method method)
            throws DataSourceInterceptorException {

        // 判断是否已经确定固定数据源，若已确定则不再重复确定（越上层优先级越高）
        if (EasyMsMasterSlaveDataSourceHolder.isFixedDataSource()) {
            return proceed(methodInvocation);
        }

        // 开启固定数据源
        try {
            EasyMsMasterSlaveDataSourceHolder.fixedDataSource();
            return proceed(methodInvocation);
        } finally {
            EasyMsMasterSlaveDataSourceHolder.clearFixedDataSource();
        }
    }

}